package com.burst.reptile.framework.websocket.sendone;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.framework.websocket.WebSocketConfigurator;

import lombok.extern.slf4j.Slf4j;

/**
 * 一对一发送消息
 * 
 * @author wujin
 *
 * @date: 2020-9-1 13:46:49
 */
@ServerEndpoint(value = "/app/chat/{username}", configurator = WebSocketConfigurator.class)
@Component
@Slf4j
public class MyOneServer {

	/**
	 * 用于存放所有在线客户端
	 */
	private static Map<String, Session> clients = new ConcurrentHashMap<>();

	@OnOpen
	public void onOpen(Session session, @PathParam(value = "username") String userName, EndpointConfig endpointConfig) {
		clients.put(userName, session);
	}

	@OnClose
	public void onClose(Session session, @PathParam(value = "username") String userName, CloseReason closeReason) {
		clients.remove(userName);
	}

	@OnError
	public void onError(Session session, @PathParam(value = "username") String userName, Throwable throwable) {
		if (clients.get(userName) != null) {
			log.info("发生了错误,移除客户端: {},{}", userName, throwable.getMessage());
			clients.remove(userName);
		}
	}

	@OnMessage
	public void onMessage(String message) {
		Message msg = JSONObject.parseObject(message, Message.class);
		this.sendTo(msg);
	}

	/**
	 * 发送消息
	 *
	 * @param message 消息对象
	 */
	private void sendTo(Message message) {
		Session s = clients.get(message.getUserName());
		if (ToolUtil.isNotEmpty(s)) {
			try {
				Map<String, Object> map = new HashMap<>();
				map.put("data", "success");
				s.getBasicRemote().sendText(JSONObject.toJSONString(map));
			} catch (IOException e) {
				log.info("客户端发送消息: {}，失败", message.getUserName());
			}
		} 
	}
	
	
	/**
	 * 发送消息
	 *
	 * @param message 消息对象
	 */
	public void sendTo(String userName) {
		Session s = clients.get(userName);
		if (ToolUtil.isNotEmpty(s)) {
			try {
				Map<String, Object> map = new HashMap<>();
				map.put("data", "success");
				s.getBasicRemote().sendText(JSONObject.toJSONString(map));
			} catch (IOException e) {
				log.info("客户端发送消息: {}，失败", userName);
			}
		} 
	}
	
}
